#coding:utf-8
import os

from PyQt4 import QtCore
from PyQt4 import QtGui

from gui.MainWindow import Ui_MainWindow
from .Connector import Connector

from .Extension.OnlineResponse import OnlineResponse

from twisted.internet import reactor

from twisted.words.xish import domish

from widgets import ProfilesDialog

from include.IqQuery import IqQuery
from include.Addins import extractUserInfo,join
from include.configobj import ConfigObj
from include import Utils

class MainClient(QtGui.QMainWindow):
        def __init__(self,homeDir=None,parent=None):
                super(MainClient,self).__init__(parent)
                ui = Ui_MainWindow()
                ui.setupUi(self)
                self.config = None
                self.connection = None 
                self.homeDir = Utils.getHomeDir()#### FIXME!
                self.rootDir = unicode(self.homeDir)#### FIXME!
                Utils.loadConfig(self) #### FIXME!
                profiles = Utils.getProfiles(self.rootDir) #### FIXME!
                #if  not profiles :
                # @first start dialog #TODO!
                #self.tray = QtGui.QSystemTrayIcon ###TODO
                #self.tray.show()###TODO
        def createNewProfile(self,jid,password):
                self.homeDir = os.path.join(self.rootDir,join(unicode(jid),"-profile"))
                Utils.makeHomeDir(self.homeDir)
                with open(os.path.join(self.homeDir,"config.ini")) as _file:
                        self.config.write(_file)
                Utils.loadConfig(self)
                self.config["jid"] = jid
                self.config["password"] = password
                self.config.save()
        @QtCore.pyqtSlot("const QString &")
        @QtCore.pyqtSlot("PyQt_PyObject")
        def changeProfile(self,jid):
                pass
        @QtCore.pyqtSlot()
        def connect(self):
                self.connection = Connector(self.config["jid"],self.config["password"],self.config["port"],self)
                self.connection.openStream.connect(self.auth)
                self.connection.connect()
        @QtCore.pyqtSlot(bool)
        def auth(self,result):
                if result is True:
                        self.connection.send(self.connection.createPresenceNode(0))
        @QtCore.pyqtSlot("PyQt_PyObject")
        def onlineDerrived(self,xml):
                pass
        @QtCore.pyqtSlot("PyQt_PyObject")
        def rawStream(self,xml):
                pass
        @QtCore.pyqtSlot()
        def getProfile(self):
                iq = self.connection.callUserProfile(self.connection.selfJid.user)
                @iq.response.connect
                @QtCore.pyqtSlot("PyQt_PyObject")
                def response(xml):
                        userNode = xml | extractUserInfo
                        print userNode
        def saveConfigBeforeExit(self):
                self.config.save()